<?php  
class ControllerProductArticle extends Controller {
	private $error = array(); 
	
	public function index() { 
		$this->language->load('product/article');
	
		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home'),			
			'separator' => false
		);
		
		$this->load->model('catalog/new');	
		
		if (isset($this->request->get['newid'])) {
			$newid = '';
				
			foreach (explode('_', $this->request->get['newid']) as $newid_id) {
				if (!$newid) {
					$newid = $newid_id;
				} else {
					$newid .= '_' . $newid_id;
				}
				
				$new_info = $this->model_catalog_new->getNew($newid_id);
				
				if ($new_info) {
					$this->data['breadcrumbs'][] = array(
						'text'      => $new_info['name'],
						'href'      => $this->url->link('product/new', 'newid=' . $newid),
						'separator' => $this->language->get('text_separator')
					);
				}
			}
		}
		
		$this->load->model('catalog/topic');	
		
		if (isset($this->request->get['topic_id'])) {
			$this->data['breadcrumbs'][] = array( 
				'text'      => $this->language->get('text_brand'),
				'href'      => $this->url->link('product/topic'),
				'separator' => $this->language->get('text_separator')
			);	
				
			$topic_info = $this->model_catalog_topic->getManufacturer($this->request->get['topic_id']);

			if ($topic_info) {	
				$this->data['breadcrumbs'][] = array(
					'text'	    => $topic_info['name'],
					'href'	    => $this->url->link('product/topic/product', 'topic_id=' . $this->request->get['topic_id']),					
					'separator' => $this->language->get('text_separator')
				);
			}
		}
		
		if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_tag'])) {
			$url = '';
			
			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . $this->request->get['filter_name'];
			}
						
			if (isset($this->request->get['filter_tag'])) {
				$url .= '&filter_tag=' . $this->request->get['filter_tag'];
			}
						
			if (isset($this->request->get['filter_description'])) {
				$url .= '&filter_description=' . $this->request->get['filter_description'];
			}
			
			if (isset($this->request->get['filter_new_id'])) {
				$url .= '&filter_new_id=' . $this->request->get['filter_new_id'];
			}	
						
			$this->data['breadcrumbs'][] = array(
				'text'      => $this->language->get('text_search'),
				'href'      => $this->url->link('product/search', $url),
				'separator' => $this->language->get('text_separator')
			);	
		}
		
		if (isset($this->request->get['article_id'])) {
			$article_id = $this->request->get['article_id'];
		} else {
			$article_id = 0;
		}
		
		$this->load->model('catalog/article');
		
		$article_info = $this->model_catalog_article->getArticle($article_id);
		
		$this->data['article_info'] = $article_info;
		
		if ($article_info) {
			$url = '';
			
			if (isset($this->request->get['newid'])) {
				$url .= '&newid=' . $this->request->get['newid'];
			}
			
			if (isset($this->request->get['topic_id'])) {
				$url .= '&topic_id=' . $this->request->get['topic_id'];
			}			

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . $this->request->get['filter_name'];
			}
						
			if (isset($this->request->get['filter_tag'])) {
				$url .= '&filter_tag=' . $this->request->get['filter_tag'];
			}
			
			if (isset($this->request->get['filter_description'])) {
				$url .= '&filter_description=' . $this->request->get['filter_description'];
			}	
						
			if (isset($this->request->get['filter_new_id'])) {
				$url .= '&filter_new_id=' . $this->request->get['filter_new_id'];
			}
												
			$this->data['breadcrumbs'][] = array(
				'text'      => $article_info['name'],
				'href'      => $this->url->link('product/article', $url . '&article_id=' . $this->request->get['article_id']),
				'separator' => $this->language->get('text_separator')
			);			
			
			$this->document->setTitle($article_info['name']);
			$this->document->setDescription($article_info['meta_description']);
			$this->document->setKeywords($article_info['meta_keyword']);
			$this->document->addLink($this->url->link('product/article', 'article_id=' . $this->request->get['article_id']), 'canonical');
			
			$this->data['heading_title'] = $article_info['name'];
			
			$this->data['text_select'] = $this->language->get('text_select');
			$this->data['text_topic'] = $this->language->get('text_topic');
			$this->data['text_author'] = $this->language->get('text_author');
			$this->data['text_or'] = $this->language->get('text_or');
			$this->data['text_write'] = $this->language->get('text_write');
			$this->data['text_note'] = $this->language->get('text_note');
			$this->data['text_share'] = $this->language->get('text_share');
			$this->data['text_wait'] = $this->language->get('text_wait');
			$this->data['text_tags'] = $this->language->get('text_tags');
			
			$this->data['entry_name'] = $this->language->get('entry_name');
			$this->data['entry_review'] = $this->language->get('entry_review');
			$this->data['entry_rating'] = $this->language->get('entry_rating');
			$this->data['entry_good'] = $this->language->get('entry_good');
			$this->data['entry_bad'] = $this->language->get('entry_bad');
			$this->data['entry_captcha'] = $this->language->get('entry_captcha');
			
			$this->data['button_cart'] = $this->language->get('button_cart');
			$this->data['button_wishlist'] = $this->language->get('button_wishlist');
			$this->data['button_compare'] = $this->language->get('button_compare');			
			$this->data['button_upload'] = $this->language->get('button_upload');
			$this->data['button_continue'] = $this->language->get('button_continue');
			
			$this->load->model('catalog/review');

			$this->data['tab_description'] = $this->language->get('tab_description');
			$this->data['tab_attribute'] = $this->language->get('tab_attribute');
			$this->data['tab_review'] = sprintf($this->language->get('tab_review'), $this->model_catalog_review->getTotalReviewsByProductId($this->request->get['article_id']));
			$this->data['tab_related'] = $this->language->get('tab_related');
			
			$this->data['article_id'] = $this->request->get['article_id'];
			$this->data['topic'] = $article_info['topic'];
			$this->data['topic'] = $this->url->link('product/topic/product', 'topic_id=' . $article_info['topic_id']);
			$this->data['author'] = $article_info['author'];
			$this->data['meta_des'] = $article_info['meta_description'];
			$this->data['date_available'] = $this->translateDate(date('D d-m-Y', strtotime($article_info['date_available'])));
			$this->load->model('tool/image');
			$this->data['topics']=array();
			$data = array(
				'filter_topic_id' 	 => $article_info['topic_id'], 
				'sort'               => 'p.date_added'
			);
			$results=$this->model_catalog_article->getArticles($data);
			foreach ($results as $result){
				if($result['article_id']==$article_id){
					continue;
				}
				if ($result['image']) {
					$image = $this->model_tool_image->resize($result['image'], $this->config->get('config_image_related_width'), $this->config->get('config_image_related_height'));
				} else {
					$image = false;
				}
				$this->data['topics'][] = array(
					'article_id' => $result['article_id'],
					'thumb'   	 => $image,
					'name'    	 => $result['name'],
					'href'    	 => $this->url->link('product/article', 'article_id=' . $result['article_id']),
					'author'     =>$result['author'],
					'date_available' => $this->translateDate(date('D d-m-Y', strtotime($result['date_available'])))
				);
			}
			if ($article_info['image']) {
				$this->data['popup'] = $this->model_tool_image->resize($article_info['image'], 800, 800);
			} else {
				$this->data['popup'] = '';
			}
			
			if ($article_info['image']) {
				$this->data['thumb'] = $this->model_tool_image->resize($article_info['image'], 250, 250);
			} else {
				$this->data['thumb'] = '';
			}
			
			$this->data['description'] = html_entity_decode($article_info['description'], ENT_QUOTES, 'UTF-8');
			$this->data['articles'] = array();
			
			$results = $this->model_catalog_article->getArticleRelated($this->request->get['article_id']);
			
			foreach ($results as $result) {
				if ($result['image']) {
					$image = $this->model_tool_image->resize($result['image'], $this->config->get('config_image_related_width'), $this->config->get('config_image_related_height'));
				} else {
					$image = false;
				}
				
							
				$this->data['articles'][] = array(
					'article_id' => $result['article_id'],
					'thumb'   	 => $image,
					'name'    	 => $result['name'],
					'href'    	 => $this->url->link('product/article', 'article_id=' . $result['article_id']),
					'author'     =>$result['author'],
					'date_available' => $this->translateDate(date('D d-m-Y', strtotime($result['date_available'])))
				);
			}	
			
			$this->data['tags'] = array();
					
			$results = $this->model_catalog_article->getArticleTags($this->request->get['article_id']);
			
			foreach ($results as $result) {
				$this->data['tags'][] = array(
					'tag'  => $result['tag'],
					'href' => $this->url->link('product/search', 'filter_tag=' . $result['tag'])
				);
			}
			
			$this->model_catalog_article->updateViewed($this->request->get['article_id']);
			
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/article.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/product/article.tpl';
			} else {
				$this->template = 'default/template/product/article.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
						
			$this->response->setOutput($this->render());
		} else {
			$url = '';
			
			if (isset($this->request->get['newid'])) {
				$url .= '&newid=' . $this->request->get['newid'];
			}
			
			if (isset($this->request->get['topic_id'])) {
				$url .= '&topic_id=' . $this->request->get['topic_id'];
			}			

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . $this->request->get['filter_name'];
			}	
					
			if (isset($this->request->get['filter_tag'])) {
				$url .= '&filter_tag=' . $this->request->get['filter_tag'];
			}
							
			if (isset($this->request->get['filter_description'])) {
				$url .= '&filter_description=' . $this->request->get['filter_description'];
			}
					
			if (isset($this->request->get['filter_new_id'])) {
				$url .= '&filter_new_id=' . $this->request->get['filter_new_id'];
			}
								
      		$this->data['breadcrumbs'][] = array(
        		'text'      => $this->language->get('text_error'),
				'href'      => $this->url->link('product/article', $url . '&article_id=' . $article_id),
        		'separator' => $this->language->get('text_separator')
      		);			
		
      		$this->document->setTitle($this->language->get('text_error'));

      		$this->data['heading_title'] = $this->language->get('text_error');

      		$this->data['text_error'] = $this->language->get('text_error');

      		$this->data['button_continue'] = $this->language->get('button_continue');

      		$this->data['continue'] = $this->url->link('common/home');

			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
			} else {
				$this->template = 'default/template/error/not_found.tpl';
			}
			
			$this->children = array(
				'common/column_left',
				'common/column_right',
				'common/content_top',
				'common/content_bottom',
				'common/footer',
				'common/header'
			);
						
			$this->response->setOutput($this->render());
    	}
  	}
	
	public function review() {
    	$this->language->load('product/article');
		
		$this->load->model('catalog/review');

		$this->data['text_no_reviews'] = $this->language->get('text_no_reviews');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}  
		
		$this->data['reviews'] = array();
		
		$review_total = $this->model_catalog_review->getTotalReviewsByProductId($this->request->get['article_id']);
			
		$results = $this->model_catalog_review->getReviewsByProductId($this->request->get['article_id'], ($page - 1) * 5, 5);
      		
		foreach ($results as $result) {
        	$this->data['reviews'][] = array(
        		'author'     => $result['author'],
				'text'       => strip_tags($result['text']),
				'rating'     => (int)$result['rating'],
        		'reviews'    => sprintf($this->language->get('text_reviews'), (int)$review_total),
        		'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
        	);
      	}			
			
		$pagination = new Pagination();
		$pagination->total = $review_total;
		$pagination->page = $page;
		$pagination->limit = 5; 
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('product/article/review', 'article_id=' . $this->request->get['article_id'] . '&page={page}');
			
		$this->data['pagination'] = $pagination->render();
		
		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/review.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/product/review.tpl';
		} else {
			$this->template = 'default/template/product/review.tpl';
		}
		
		$this->response->setOutput($this->render());
	}
	
	public function write() {
		$this->language->load('product/article');
		
		$this->load->model('catalog/review');
		
		$json = array();
		
		if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
			$json['error'] = $this->language->get('error_name');
		}
		
		if ((utf8_strlen($this->request->post['text']) < 25) || (utf8_strlen($this->request->post['text']) > 1000)) {
			$json['error'] = $this->language->get('error_text');
		}

		if (!$this->request->post['rating']) {
			$json['error'] = $this->language->get('error_rating');
		}

		if (!isset($this->session->data['captcha']) || ($this->session->data['captcha'] != $this->request->post['captcha'])) {
			$json['error'] = $this->language->get('error_captcha');
		}
				
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && !isset($json['error'])) {
			$this->model_catalog_review->addReview($this->request->get['article_id'], $this->request->post);
			
			$json['success'] = $this->language->get('text_success');
		}
		
		$this->response->setOutput(json_encode($json));
	}
	
	public function captcha() {
		$this->load->library('captcha');
		
		$captcha = new Captcha();
		
		$this->session->data['captcha'] = $captcha->getCode();
		
		$captcha->showImage();
	}
	
	public function upload() {
		$this->language->load('product/article');
		
		$json = array();
		
		if (!empty($this->request->files['file']['name'])) {
			$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
			
			if ((strlen($filename) < 3) || (strlen($filename) > 128)) {
        		$json['error'] = $this->language->get('error_filename');
	  		}	  	
			
			$allowed = array();
			
			$filetypes = explode(',', $this->config->get('config_upload_allowed'));
			
			foreach ($filetypes as $filetype) {
				$allowed[] = trim($filetype);
			}
			
			if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
				$json['error'] = $this->language->get('error_filetype');
       		}	
						
			if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
				$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
			}
		} else {
			$json['error'] = $this->language->get('error_upload');
		}
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && !isset($json['error'])) {
			if (is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
				$file = basename($filename) . '.' . md5(rand());
				
				// Hide the uploaded file name sop people can not link to it directly.
				$this->load->library('encryption');
				
				$encryption = new Encryption($this->config->get('config_encryption'));
				
				$json['file'] = $encryption->encrypt($file);
				
				move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $file);
			}
						
			$json['success'] = $this->language->get('text_upload');
		}	
		
		$this->response->setOutput(json_encode($json));		
	}
	public function translateDate($date){
		$strday='';
		$day='';
		
		if(isset($date)){
			$array=explode(" ",$date);
			$day=$array[0];
			$date=$array[1];
			if(isset($day)){
				switch ($day){
					case "Mon":
						$strday='Thứ Hai';
						break;
					case "Tue":
						$strday='Thứ Ba';
						break;
					case "Wed":
						$strday='Thứ Tư';
						break;
					case "‎Thu":
						$strday='Thứ Năm';
						break;
					case "Fri":
						$strday='Thứ Sáu';
						break;
					case "Sat":
						$strday='Thứ Bảy';
						break;
					case "Sun":
						$strday='Chủ Nhật';
						break;	
				}
			}
		}
		return $strday." ".$date;
	}
}
?>